package com.android.mios.util;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;

public class AsyncImageLoader {

	private HashMap<Object, SoftReference<Bitmap>> imageCache;
	private Context context;

	public AsyncImageLoader(Context context) {
		imageCache = new HashMap<Object, SoftReference<Bitmap>>();
		this.context = context;
	}

	public Bitmap loadDrawable(final Object name,
			final ImageCallback imageCallback) {
		if (imageCache.containsKey(name)) {
			SoftReference<Bitmap> softReference = imageCache.get(name);
			Bitmap bitmap = softReference.get();
			if (bitmap != null) {
				return bitmap;
			}
		}
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Bitmap) message.obj, name);
			}
		};
		new Thread() {
			@Override
			public void run() {
				Bitmap bitmap = loadImageFromName(name);
				imageCache.put(name, new SoftReference<Bitmap>(bitmap));
				Message message = handler.obtainMessage(0, bitmap);
				handler.sendMessage(message);
			}
		}.start();
		return null;
	}

	public Bitmap loadImageFromName(Object name) {

		Bitmap bitmap = null;
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = false;
		opts.inSampleSize = 4;
		if (name instanceof Integer) {

			bitmap = BitmapFactory.decodeResource(context.getResources(),
					(Integer) name, opts);
		}
		if (name instanceof String) {

			File file = new File(Global.getInstance().getFileForPath(
					Global.getInstance().getSkinPath()), (String) name);

			if (file != null)
				bitmap = BitmapFactory.decodeFile(file.getPath(),opts);
		}
		return bitmap;
	}

	public interface ImageCallback {
		public void imageLoaded(Bitmap imageDrawable, Object name);
	}

}
